package com.example.furniture.controller;

import com.example.furniture.dto.LoginRequest;
import com.example.furniture.dto.LoginResponse;
import com.example.furniture.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 提供用户认证相关的API接口
 * 
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*") // 允许跨域访问，用于前端调用
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    private final AuthService authService;

    /**
     * 构造函数，注入认证服务
     * 
     * @param authService 认证服务实例
     */
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    /**
     * 用户登录
     * 
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            logger.info("用户登录请求: {}", loginRequest.getUsername());
            
            LoginResponse response = authService.login(loginRequest);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", response);
            result.put("timestamp", System.currentTimeMillis());
            
            logger.info("用户登录成功: {}", loginRequest.getUsername());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("用户登录失败: {}", loginRequest.getUsername(), e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
    }

    /**
     * 验证令牌
     * 
     * @param token JWT令牌
     * @return 验证结果
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateToken(@RequestParam("token") String token) {
        try {
            logger.debug("验证令牌请求");
            
            boolean isValid = authService.validateToken(token);
            String username = null;
            
            if (isValid) {
                username = authService.getUsernameFromToken(token);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("valid", isValid);
            result.put("username", username);
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("令牌验证失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("valid", false);
            result.put("message", "令牌验证失败");
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }
    }

    /**
     * 用户登出
     * 
     * @return 登出结果
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout() {
        try {
            logger.info("用户登出请求");
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登出成功");
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            logger.error("用户登出失败", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "登出失败");
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 健康检查
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "认证服务正常运行");
        result.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(result);
    }
}
